<template>
  <div>
    <NCard class="list-card-container h-100 position-relative" :bordered="false">
      <NForm ref="formRef" label-width="120px" :data="formData" reset-type="initial" label-align="top" :rules="rules">
        <NRow :gutter="[12, 12]">
          <NCol :span="12">
            <NFormItem label="订单类型" name="orderType"> </NFormItem>
          </NCol>
        </NRow>
      </NForm>

      <div v-for="(subOrder, index) in formData.subOrder" :key="index">
        <NForm :rules="getSubOrderRules(index)" ref="el => subOrderRefs[index] = el">
          <NRow :gutter="[12, 12]">
            <NCol :span="6">
              <NFormItem :path="`deliveryTime-${index}`" label="发货时间">
                <NInput type="text" />
              </NFormItem>
            </NCol>
          </NRow>
        </NForm>
      </div>

      <NButton type="default" variant="outline" @click="addSubOrder"> <AddCircleIcon /> 添加子订单 </NButton>

      <NButton type="primary" @click="submitForm">保存</NButton>
    </NCard>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { NCard, NForm, NRow, NCol, NFormItem, NButton, NInput } from 'naive-ui'

const formData = ref<{
  orderType: number
  subOrder: {
    deliveryTime: string
  }[]
}>({
  orderType: 1,
  subOrder: [],
})

const rules = ref({
  orderType: [{ required: true, message: '请选择订单类型' }],
})

const subOrderRefs = ref<(NForm | null)[]>([])

const getSubOrderRules = (index: number) => ({
  [`deliveryTime-${index}`]: [{ required: true, message: '请选择订单类型' }],
})

const addSubOrder = () => {
  formData.value.subOrder.push({
    deliveryTime: '',
  })
  subOrderRefs.value.push(null)
}

const submitForm = async () => {
  const allValid = await Promise.all(subOrderRefs.value.map((formRef) => formRef?.validate())).then((results) =>
    results.every((valid) => valid),
  )
  if (allValid) {
    console.log('所有表单验证通过')
  } else {
    console.error('部分表单验证失败')
  }
}
</script>

<style scoped>
.sub-order {
  margin-bottom: 10px;
}
</style>
